package com.ckx.config.nacos;

import com.alibaba.cloud.nacos.registry.NacosServiceRegistry;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.serviceregistry.Registration;
import org.springframework.context.SmartLifecycle;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class GracefulShutdown implements SmartLifecycle {

    private volatile boolean running;

    @Resource
    private Registration registration;

    @Resource
    private NacosServiceRegistry serviceRegistry;

    @Override
    public void start() {
        this.running = true;
    }

    @Override
    public void stop() {
        try {
            this.running = false;
            serviceRegistry.deregister(registration);
        } catch (Exception e) {
            log.warn("deregister error", e);
        }
    }

    @Override
    public boolean isRunning() {
        return this.running;
    }

    @Override
    public int getPhase() {
        return SmartLifecycle.DEFAULT_PHASE - 100;
    }

}
